package com.mindainfo.groundwave.server.member.service;

import com.alibaba.fastjson.JSON;
import com.mindainfo.groundwave.common.api.member.param.*;
import com.mindainfo.groundwave.common.api.member.service.IRoleService;
import com.mindainfo.groundwave.common.api.member.vo.*;
import com.mindainfo.groundwave.common.bean.CommonResult;
import com.mindainfo.groundwave.common.bean.DataGrid;
import com.mindainfo.groundwave.common.bean.ResultFactory;
import com.mindainfo.groundwave.common.bean.TableData;
import com.mindainfo.groundwave.server.base.dao.JedisDao;
import com.mindainfo.groundwave.server.member.bean.SysMember;
import com.mindainfo.groundwave.server.member.bean.SysPermission;
import com.mindainfo.groundwave.server.member.bean.SysRole;
import com.mindainfo.groundwave.server.member.dao.IPermissionDao;
import com.mindainfo.groundwave.server.member.dao.IRoleDao;
import com.mindainfo.groundwave.server.member.dto.RolePermissionInAllTreeDto;
import com.mindainfo.groundwave.server.member.mapper.SysMemberMapper;
import com.mindainfo.groundwave.server.member.mapper.SysPermissionMapper;
import com.mindainfo.groundwave.server.member.mapper.SysRoleMapper;
import com.sun.org.apache.regexp.internal.RE;
import org.apache.logging.log4j.core.util.datetime.FastDateFormat;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by MD-01 on 2017/5/17.
 */
@Service
@Transactional
public class RoleServiceImpl implements IRoleService{

    @Resource
    private SysRoleMapper roleMapper;
    @Resource
    private SysMemberMapper memberMapper;
    @Resource
    private SysPermissionMapper permissionMapper;

    /**
     * 列表页面分页,条件查询角色列表
     */
    public CommonResult<TableData<RoleQueryListVo>> queryList(RoleQueryListParam param){

        List<SysRole> roleList = roleMapper.queryList(param.getStart(), param.getNum(), param.getKey());
        List<RoleQueryListVo> vos = new ArrayList<>();
        FastDateFormat format = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");
        for(SysRole role : roleList){
            RoleQueryListVo vo = new RoleQueryListVo();
            vo.setRoleId(role.getId());
            vo.setCreateTime(format.format(role.getCreateTime()));
            vo.setCreateMemberId(role.getCreateMemberId());

            SysMember member = memberMapper.selectById(vo.getCreateMemberId());
            if(member!=null) {
                vo.setCreateMemberName(member.getUsername());
            }
            vo.setDescription(role.getDescription());
            vo.setName(role.getName());
            vo.setTag(role.getTag());
            vo.setOrderNum(role.getOrderNum());
            List<SysPermission> permissions = permissionMapper.queryUsableByRoleId(role.getId());
            for(SysPermission permission : permissions){

                RoleQueryListVo.RolePermissionVo rpVo = new RoleQueryListVo.RolePermissionVo();
                rpVo.setName(permission.getName());
                rpVo.setParentId(permission.getParentId());
                rpVo.setPermissionId(permission.getId());
                rpVo.setType(permission.getType());
                vo.getPermissionList().add(rpVo);
            }
            vos.add(vo);
        }
        int count = roleMapper.queryListCount(param.getKey());
        TableData<RoleQueryListVo> data = new TableData<>();
        data.setData(vos);
        data.setRecordsFiltered(count);
        data.setRecordsTotal(count);
        return ResultFactory.ok(data);
    }

    /**
     * 添加/修改角色
     */
    public CommonResult<Void> save(RoleSaveParam param) {

        //新建
        if(param.getRoleId()==null){
            SysRole role = roleMapper.queryByTag(param.getTag());
            if(role!=null){
                return ResultFactory.error("该标识已经存在");
            }
            role = new SysRole();
            role.setOrderNum(param.getOrderNum());
            role.setName(param.getName());
            role.setCreateTime(new Date());

            Session session = SecurityUtils.getSubject().getSession();
            SysMember member = (SysMember) session.getAttribute("member");
            role.setCreateMemberId(member.getId());
            role.setDescription(param.getDescription());
            role.setTag(param.getTag());
            roleMapper.insert(role);
            return ResultFactory.ok();
        }

        //修改
        SysRole role = roleMapper.selectById(param.getRoleId());
        if(role==null){
            return ResultFactory.error("错误的权限编号");
        }
        role.setTag(param.getTag());
        role.setDescription(param.getDescription());
        role.setName(param.getName());
        role.setOrderNum(param.getOrderNum());
        roleMapper.updateById(role);

        return ResultFactory.ok();
    }

    /**
     * 角色页面-查看角色权限
     */
    public CommonResult<List<RoleLookPermissionsVo>> lookPermissions(RoleLookPermissionsParam param){

        List<SysPermission> permissions = permissionMapper.queryUsableByRoleId(param.getRoleId());
        List<RoleLookPermissionsVo> vos = new ArrayList<>();
        for(SysPermission permission : permissions){
            RoleLookPermissionsVo vo = new RoleLookPermissionsVo();
            vo.setPermissionId(permission.getId());
            vo.setName(permission.getName());
            vo.setParentId(permission.getParentId());
            vo.setType(permission.getType());
            vos.add(vo);
        }
        return ResultFactory.ok(vos);
    }

    /**
     * 角色页面--编辑权限树
     */
    public CommonResult<List<RoleEditPermissionsVo>> editPermissions(RoleEditPermissionsParam param){


        List<RolePermissionInAllTreeDto> list = permissionMapper.queryRolePermissionInAllTree(param.getRoleId());
        List<RoleEditPermissionsVo> vos = new ArrayList<>();
        for(RolePermissionInAllTreeDto dto :list){
            RoleEditPermissionsVo vo = new RoleEditPermissionsVo();
            vo.setHasPermission(dto.getHasPermission());
            vo.setName(dto.getName());
            vo.setParentId(dto.getParentId());
            vo.setPermissionId(dto.getPermissionId());
            vo.setType(dto.getType());
            vos.add(vo);
        }
        return ResultFactory.ok(vos);
    }
    
    
    /**
     * 设置角色的权限
     */
    public CommonResult<Void> setPermission(RoleSetPermissionParam param) {

        //删除角色-权限表
        roleMapper.deleteRolePermissionByRoleId(param.getRoleId());

        //创建对应关系
        for(Integer permissionId : param.getPermissionIdList()){
            roleMapper.insertRolePermission(param.getRoleId(),permissionId);
        }
        return ResultFactory.ok();
    }

    /**
     * 删除角色
     */
    public CommonResult<Void> toDel(RoleToDelParam param){
        SysRole role = roleMapper.selectById(param.getRoleId());
        if(role==null){
            return ResultFactory.error("错误的角色编号");
        }
        //TODO 删除角色之前应该先判断是否被绑定到用户上
        List<SysMember> sysMembers = memberMapper.querybyRoleId(param.getRoleId());
        if(sysMembers.size()>0){
            return ResultFactory.error("该角色已经绑定到用户上了,不能删除");
        }

        roleMapper.deleteById(param.getRoleId());

        //删除 角色-权限 映射
        roleMapper.deleteRolePermissionByRoleId(param.getRoleId());
        return ResultFactory.ok();
    }


    /**
     * 获取所有可用的角色
     * @return
     */
    public CommonResult<List<RoleQueryUsableAllVo>> queryUsableAll(){

        List<SysRole> roleList = roleMapper.queryUsableAll();

        List<RoleQueryUsableAllVo> vos = new ArrayList<>();
        for(SysRole role : roleList){
            RoleQueryUsableAllVo vo = new RoleQueryUsableAllVo();
            vo.setRoleId(role.getId());
            vo.setName(role.getName());
            vos.add(vo);
        }
        return ResultFactory.ok(vos);
    }
}
